﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;


namespace Kit
{
    public class GCMKit
    {
        private const string kGCMPushURL = "http://ios.ccp.com.tw/Henry/GCMPush/SendToGcm.ashx";//ios.ccp
        private const string kSoundFileCall = "c1.caf";
        private const string kMsgTypeCall = "C";


        public static void SendCallPush(string alertMsg, string from, string pushToken, int expirySeconds)
        {
            Dictionary<string, string> paramDict = new Dictionary<string, string>();
            paramDict["registration_ID"] = pushToken;
            paramDict["msgType"] = kMsgTypeCall;
            paramDict["message"] = alertMsg;
            paramDict["contentTitle"] = "iSender Call";
            paramDict["TTL"] = expirySeconds.ToString();
            paramDict["from"] = from;
            paramDict["sound"] = kSoundFileCall;

            string paramStr = Kit.ChrisKit.DictToQueryStr(paramDict, Encoding.UTF8);
            byte[] postBytes = Encoding.UTF8.GetBytes(paramStr);

            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(kGCMPushURL);
            webReq.ProtocolVersion = HttpVersion.Version11;
            webReq.Method = "POST";
            webReq.Timeout = 30 * 1000;
            webReq.KeepAlive = false;
            webReq.AllowAutoRedirect = false;
            webReq.Proxy = new WebProxy();

            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = postBytes.Length;
            using (System.IO.Stream reqStream = webReq.GetRequestStream())
            {
                reqStream.Write(postBytes, 0, postBytes.Length);
                reqStream.Flush();
                reqStream.Close();
            }

            try
            {
                HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
                System.IO.Stream respStream = webResp.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(respStream);
                string respStr = reader.ReadToEnd();

                // Cleanup
                reader.Close();
                respStream.Close();
                webResp.Close();
            }
            catch (Exception ex)
            {
                ChrisKit.SkipVar(ex);
            }
        }

    }
}